﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Web;
using System.Web.Mvc;
using HQPad.Services;
using HQPad.DAL;
using HQPad.Models;
using HQPad.Helpers;

namespace HQPad.Controllers
{
    public class CharacterImportController : BaseController
    {
        //
        // GET: /Import/

        public ActionResult Index()
        {
            return View();
        }

        // This action handles the form POST and the upload
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase fileUpload)
        {
            // Verify that the user selected a file
            if (fileUpload != null && fileUpload.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(fileUpload.FileName);

                // check file name ends with hqml or hqmlm.
                if (!fileName.ToLowerInvariant().EndsWith(".hqml") && !fileName.ToLowerInvariant().EndsWith(".hqmlm"))
                {
                    ModelState.AddModelError("fileUpload", "The uploaded file must have either an HQML or HQMLM extension.");
                    return View();
                }

                TextReader reader = null;
                XDocument hqmlDoc = null;

                try
                {

                    reader = new StreamReader(fileUpload.InputStream);

                    string xml = reader.ReadToEnd();

                    // Patch up piss poor xml formatting.
                    xml = xml.Replace("<SkillOverrides>", "");

                    // Save the hqml file to an xml document.
                    hqmlDoc = XDocument.Parse(xml, LoadOptions.None);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("fileUpload", string.Format("An error occured parsing the HQML or HQMLM xml.  {0}", ex.Message));
                    return View();
                }
                finally
                {
                    if (reader != null)
                    {
                        fileUpload.InputStream.Flush();
                        reader.Close();
                    }
                }

                IUnitOfWork context = new HQContext();
                IRulesService rulesService = new RulesService(context);
                ICharacterService characterService = new CharacterService(context);

                // Create helper and default character.
                XDocument character = CharacterRulesHelper.CreateDefaultCharacter();
                CharacterRulesHelper helper = new CharacterRulesHelper(context, character.ToString());

                string userName = AuthenticationHelper.GetCurrentUserName(HttpContext);
                string sessionId = AuthenticationHelper.GetCurrentSessionId(Request);

                // Call the character import service to convert the hqml to the hqpad xml document format.
                ICharacterImportService importService = new CharacterImportService(rulesService.GetDefaultRules().RuleSetID, userName, sessionId, characterService);

                CharacterImportResult result = importService.ConvertHQML(context, hqmlDoc, helper);

                if (result.Success)
                {
                    string name = helper.GetName();

                    // Save the new character to the scratch pad.
                    characterService.CreateScratchPadCharacter(userName, sessionId, name, characterService.CreateCharacterSlug(name), helper.GetXml());

                    context.Save(); // save work done.
                }

                // redirect to the load results page.
                return View("Results", result);
            }
            else // no file.
            {
                ModelState.AddModelError("fileUpload", "No HQML file selected.");
                return View();
            }

            // redirect back to the index action to show the form once again
            return RedirectToAction("Index");
        }
    }
}
